<template>
  <div style="display: flex;  flex-direction: column;">
    <div style="display: flex; max-height: 20px;">
      <h5 style="margin-left: 10px">项目编号</h5>
      <el-input style="margin-top: -5px; width:120px; margin-left: 10px" placeholder="请输入项目编号" v-model="projectNumber"></el-input>
      <h5 style="margin-left: 20px">项目名称</h5>
      <el-input style="margin-top: -5px; width:120px; margin-left: 10px" placeholder="请输入项目名称" v-model="projectName" ></el-input>
      <el-button type="primary" style="margin-top: -5px; margin-left: 30px" icon="el-icon-search" @click="init">查询</el-button>
      <el-button type="warning" style="margin-top: -5px; margin-left: 10px" icon="el-icon-refresh" @click="reset">重置</el-button>
    </div>
    <div style="display: flex; margin-top: 20px">
      <el-table :data="tableData" style="width: 100%" height="500">
        <el-table-column fixed label="序号" width="45">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="publicityName" label="公示名称"></el-table-column>
        <el-table-column fixed prop="projectNumber" label="项目编号"></el-table-column>
        <el-table-column fixed prop="projectName" label="项目名称"></el-table-column>
        <el-table-column prop="dealer" label="成交人（品牌）"></el-table-column>
        <el-table-column prop="status" label="公告状态">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status <= 3" type="warning" effect="circle">待公示</el-tag>
            <el-tag v-else-if="scope.row.status === 4" type="primary" effect="circle">公示中</el-tag>
            <el-tag v-else type="info" effect="circle">已结束</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publicityDate" label="公示时间" width="180"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button v-if ="scope.row.status <= 3" type="primary" @click="handlePublicity(scope.row)">发布公示</el-button>
            <el-button v-if="scope.row.status >= 4" type="success" @click="handleLook(scope.row)">查看</el-button>
            <el-button v-if="scope.row.status >= 4" type="warning" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.status >= 4" type="danger" @click="confirmDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="padding: 10px 0;margin-left: 800px">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 15, 20, 30]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
<!--    发布公示-->
    <el-dialog :visible.sync="dialogPublicPublicityVisible"
               :custom-class="'slide-right-dialog'"
    >
      <div class="dialog-content">
        <div style="border: 2px solid #409EFF; border-radius: 5px; padding: 20px; background-color: #f2f7fc; margin-bottom: 20px;">
          <el-descriptions :title="publicPublicityForm.title" style="display: inline-block;margin-top: -100px" column="4" size="mini">
            <el-descriptions-item label="采购方式">{{publicPublicityForm.procurementMethod}}</el-descriptions-item>
            <el-descriptions-item label="项目预算（万元）">{{ publicPublicityForm.budget }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="dialog-title"><i class="el-icon-d-arrow-right"></i>发布公示</div>
        <el-card>
        <el-form :model="publicPublicityForm" :rules="rules" :ref="publicPublicityForm" label-width="120px" class="demo-ruleForm custom-form" style="margin-top: 30px">
          <el-form-item label="公示名称" prop="publicityName" readonly>
            <el-input v-model="publicPublicityForm.publicityName"></el-input>
          </el-form-item>
          <el-form-item label="成交人（品牌）" prop="dealer" readonly>
            <el-button v-model="publicPublicityForm.dealer" icon="el-icon-plus" @click="showDialog(publicPublicityForm.projectNumber)" type="primary">选择成交人</el-button>
            <el-tag type="info">填写品牌名称</el-tag>
          </el-form-item>
          <el-dialog
              width="50%"
              title="选择成交人"
              :visible.sync="dialogDealerVisible"
              append-to-body>
            <el-table :data="dealerData" style="width: 100%" border>
              <el-table-column label="序号" prop="index">
                <template slot-scope="scope">
                  {{ scope.$index + 1 }} <!-- 使用 $index 来显示序号 -->
                </template>
              </el-table-column>
              <el-table-column label="报名单位" prop="departmentName"></el-table-column>
              <el-table-column label="联系人" prop="contactPerson"></el-table-column>
              <el-table-column label="联系方式" prop="contactPhone"></el-table-column>
              <!-- 最右侧的操作列 -->
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button
                      size="mini"
                      type="primary"
                      @click="selectRow(row)"
                      :disabled="isSelected(row)"
                  >
                    {{ isSelected(row) ? '已选中' : '选择' }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 显示已选中的公司 -->
            <div v-if="selectedRows.length > 0" class="selected-list">
              <h3>已选中公司：</h3>
              <el-tag
                  v-for="(item, index) in selectedRows"
                  :key="index"
                  closable
                  @close="removeSelected(index)"
                  style="margin-right: 10px; margin-bottom: 10px;"
              >
                {{ item.departmentName }}
              </el-tag>
            </div>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogDealerVisible = false">取 消</el-button>
              <el-button type="primary" @click="handleDealer()">确 定</el-button>
            </div>
          </el-dialog>
          <el-form-item label="公示附件" prop="publicityFileUrl">
            <el-upload
                :action="'http://' + serverIp() + ':8081/jdyfy/file/upload'"
                :show-file-list="true"
                :on-success="handleAnnounFile"
                :on-error="handleAnnounFileError">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传不超过50mb的文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="公示时间" prop="deadline" readonly>
            <div class="block">
              <el-date-picker
                  v-model="publicPublicityForm.dateRange"
                  type="daterange"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions">
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="公示内容" prop="publicityText" readonly>
            <el-input type="textarea" v-model="publicPublicityForm.publicityText"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitPublicity">发布公示</el-button>
            <el-button @click="dialogPublicPublicityVisible = false">关闭</el-button>
          </el-form-item>
        </el-form>
        </el-card>
      </div>
    </el-dialog>
<!--    查看公示-->
    <el-dialog :visible.sync="dialogLookVisible"
               :custom-class="'slide-right-dialog'"
    >
      <div class="dialog-content">
        <div style="border: 2px solid #409EFF; border-radius: 5px; padding: 20px; background-color: #f2f7fc; margin-bottom: 20px;">
          <el-descriptions :title="LookPublicityForm.title" style="display: inline-block;margin-top: -100px" column="4" size="mini">
            <el-descriptions-item label="采购方式">{{LookPublicityForm.procurementMethod}}</el-descriptions-item>
            <el-descriptions-item label="项目预算（万元）">{{ LookPublicityForm.budget }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="dialog-title"><i class="el-icon-d-arrow-right"></i>查看公示</div>
        <el-card>
        <el-form :model="LookPublicityForm" :rules="rules" :ref="LookPublicityForm" label-width="120px" class="demo-ruleForm custom-form" style="margin-top: 30px">
          <el-form-item label="公示名称" prop="publicityName">
            <el-input v-model="LookPublicityForm.publicityName" readonly></el-input>
          </el-form-item>
          <el-form-item label="成交人（品牌）" prop="dealer">
            <el-input v-model="LookPublicityForm.dealer" type="primary" readonly></el-input>
          </el-form-item>
          <el-form-item label="公示时间" prop="deadline" >
            <el-input v-model="LookPublicityForm.publicityDate" readonly></el-input>
          </el-form-item>
          <el-form-item label="公示附件" prop="publicityFileUrl">
            <a :href="LookPublicityForm.publicityFileUrl" target="_blank" v-if="LookPublicityForm.publicityFileUrl">公示附件</a>
          </el-form-item>
          <el-form-item label="公示内容" prop="publicityText" >
            <el-input type="textarea" v-model="LookPublicityForm.publicityText" readonly></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="dialogLookVisible = false">关闭</el-button>
          </el-form-item>
        </el-form>
        </el-card>
      </div>
    </el-dialog>
<!--    编辑公示-->
    <el-dialog :visible.sync="dialogEditVisible"
               :custom-class="'slide-right-dialog'"
    >
      <div class="dialog-content">
        <div style="border: 2px solid #409EFF; border-radius: 5px; padding: 20px; background-color: #f2f7fc; margin-bottom: 20px;">
          <el-descriptions :title="editPublicityForm.title" style="display: inline-block;margin-top: -100px" column="4" size="mini">
            <el-descriptions-item label="采购方式">{{editPublicityForm.procurementMethod}}</el-descriptions-item>
            <el-descriptions-item label="项目预算（万元）">{{ editPublicityForm.budget }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="dialog-title"><i class="el-icon-d-arrow-right"></i>编辑公示</div>
        <el-card>
        <el-form :model="editPublicityForm" :rules="rules" :ref="editPublicityForm" label-width="120px" class="demo-ruleForm custom-form" style="margin-top: 30px">
          <el-form-item label="公示名称" prop="publicityName" readonly>
            <el-input v-model="editPublicityForm.publicityName"></el-input>
          </el-form-item>
          <el-form-item label="成交人（品牌）" prop="dealer">
            <el-button v-model="editPublicityForm.dealer" icon="el-icon-plus" @click="showDialog(editPublicityForm.projectNumber)" type="primary">选择成交人</el-button>
            <el-tag type="info">填写品牌名称</el-tag>
          </el-form-item>
          <el-dialog
              width="50%"
              title="选择成交人"
              :visible.sync="dialogDealerVisible"
              append-to-body>
            <el-table :data="dealerData" style="width: 100%" border>
              <el-table-column label="序号" prop="index">
                <template slot-scope="scope">
                  {{ scope.$index + 1 }} <!-- 使用 $index 来显示序号 -->
                </template>
              </el-table-column>
              <el-table-column label="报名单位" prop="departmentName"></el-table-column>
              <el-table-column label="联系人" prop="contactPerson"></el-table-column>
              <el-table-column label="联系方式" prop="contactPhone"></el-table-column>
              <!-- 最右侧的操作列 -->
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button
                      size="mini"
                      type="primary"
                      @click="selectRow(row)"
                      :disabled="isSelected(row)"
                  >
                    {{ isSelected(row) ? '已选中' : '选择' }}
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 显示已选中的公司 -->
            <div v-if="selectedRows.length > 0" class="selected-list">
              <h3>已选中公司：</h3>
              <el-tag
                  v-for="(item, index) in selectedRows"
                  :key="index"
                  closable
                  @close="removeSelected(index)"
                  style="margin-right: 10px; margin-bottom: 10px;"
              >
                {{ item.departmentName }}
              </el-tag>
            </div>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogDealerVisible = false">取 消</el-button>
              <el-button type="primary" @click="handleDealer()">确 定</el-button>
            </div>
          </el-dialog>
          <el-form-item label="公示时间" prop="deadline">
            <div class="block">
              <el-date-picker
                  v-model="editPublicityForm.dateRange"
                  type="daterange"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions">
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="公示附件" prop="publicityFileUrl">
            <el-upload
                :action="'http://'+serverIp() + ':8081/jdyfy/file/upload'"
                :show-file-list="true"
                :on-success="handleAnnounFile"
                :on-error="handleAnnounFileError">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传不超过50mb的文件</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="公示内容" prop="publicityText">
            <el-input type="textarea" v-model="editPublicityForm.publicityText"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveEdit">确认修改</el-button>
            <el-button @click="dialogEditVisible = false">关闭</el-button>
          </el-form-item>
        </el-form>
        </el-card>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {addProject, getProjectPageByStatusSpace} from "@/api/project";
import {getAnnouncementsByProjectNumbers, getEnlistDepartmentCount} from "@/api/announcement";
import {addPublicity, deletePublicityByName, getPublicitysByProjectNumbers} from "@/api/publicity";
import {getDepartByDepartName, getDepartsByDepartNames} from "@/api/department";
import {serverIp} from "../../../../public/config.js";

export default {
  name: "Announcement",
  data() {
    return {
      tableData: [],
      dealerData: [],
      procurementMethod:'',
      projectNumber: "",
      projectName: "",
      pageNum: 1,
      total: 0,
      pageSize: 10,
      dialogPublicPublicityVisible: false, // 发布公示
      dialogDealerVisible: false, // 选择成交人
      dialogLookVisible: false, // 查看公示
      dialogEditVisible: false, // 编辑公示
      updateForm: {},
      publicPublicityForm: {},
      LookPublicityForm: {},
      editPublicityForm: {},
      fileUrl: "",
      pickerOptions: {
        shortcuts: [{
          text: '最近三天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            end.setTime(end.getTime() + 3600 * 1000 * 24 * 3);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      form: {},
      selectedRows: [], // 存储已选择的行
    }
  },
  created() {
    this.init();
  },
  methods: {
    serverIp() {
      return serverIp
    },
    init() {//初始化页面
      getProjectPageByStatusSpace(this.pageNum, this.pageSize, this.projectNumber, this.projectName, this.procurementMethod,4,4).then(res => {
        //根据项目名称查询公告信息
        const projects = res.records;
        const projectNumbers = projects.map(project => project.projectNumber);

        // 根据项目编号集合查询对应公示信息
        getPublicitysByProjectNumbers(projectNumbers).then(publicitys => {
            // 将公告信息添加到每个项目中
            projects.forEach(project => {
              const publicity = publicitys.find(a => a.projectNumber === project.projectNumber);
              // 添加公告名和数量到项目中
              project.publicityName = publicity ? publicity.publicityName : "无公示";
              project.dealer = publicity ? publicity.dealer : "无公示";
              project.publicityId = publicity ? publicity.publicityId : "无公示";
              project.publicityText = publicity ? publicity.publicityText : "无公示";
              project.publicityFileUrl = publicity ? publicity.publicityFileUrl : "无公示";

              // 添加公告的开始时间和结束时间
              const startTime = publicity ? publicity.publicityStartTime : "无公示";
              const endTime = publicity ? publicity.publicityEndTime : "无公示";
              if (startTime && endTime) {
                project.publicityDate =`${startTime} - ${endTime}`;
              }
            });
            console.log(projects);
            this.tableData = projects;
            this.total = res.total;
        });
      });
    },
    handleSizeChange(val) { // 改变页码
      this.pageSize = val;
      this.init();
    },
    handleCurrentChange(val) { // 改变每页显示条数
      this.pageNum = val;
      this.init();
    },
    handlePublicity(row) { // 发布公示
      this.publicPublicityForm.publicityName = `关于{${row.projectNumber}+${row.projectName}}的{${row.procurementMethod}}公示`
      this.publicPublicityForm.title = `${row.projectName}（招标项目编号${row.projectNumber}）`
      this.publicPublicityForm.budget = row.budget
      this.publicPublicityForm.procurementMethod = row.procurementMethod
      this.publicPublicityForm.projectNumber = row.projectNumber
      this.publicPublicityForm.status = 1
      this.dialogPublicPublicityVisible = true
    },
    async submitPublicity() { // 提交公示
      const dateStr1 = this.publicPublicityForm.dateRange[0];
      const date1 = new Date(dateStr1);
      const formattedDate1 = date1.toISOString().slice(0, 10);
      const dateStr2 = this.publicPublicityForm.dateRange[1];
      const date2 = new Date(dateStr2);
      const formattedDate2 = date2.toISOString().slice(0, 10);
      this.publicPublicityForm.publicityStartTime=formattedDate1
      this.publicPublicityForm.publicityEndTime=formattedDate2
      this.publicPublicityForm.projectNumber = this.publicPublicityForm.publicityName.split("{")[1].split("+")[0]
      this.publicPublicityForm.publicityFileUrl = this.fileUrl !== '' ? this.fileUrl : this.publicPublicityForm.publicityFileUrl
      this.fileUrl = ''
      await addPublicity(this.publicPublicityForm).then(res => {
        if(res){
          this.updateForm.projectNumber = this.publicPublicityForm.projectNumber
          this.updateForm.status = 4
          addProject(this.updateForm)
          this.$message.success('操作成功')
        }else {
          this.$message.error('操作失败')
        }
      })
      this.dialogPublicPublicityVisible = false
      this.init()
    },
    showDialog(projectNumber) { // 发布公示里层：选择成交人
      const projectNumbers = [projectNumber]
      getAnnouncementsByProjectNumbers(projectNumbers).then(announcements => {
        const announcementNames = announcements.map(announcement => announcement.announcementName);
        getEnlistDepartmentCount(announcementNames).then(ad => {
          const annoDepartment = ad.reduce((acc, curr) => {
            const announcementName = curr.announcementName;
            if (acc[announcementName]) {
              acc[announcementName].push(curr.departmentName)
            } else {
              acc[announcementName] = [curr.departmentName];
            }
            return acc
          }, {});
          getDepartsByDepartNames(annoDepartment[announcements[0].announcementName]).then(res => {
            this.dealerData = res.data
          })
        })
      });
      this.dialogDealerVisible = true; // 显示对话框
    },
    // 选择某一行
    selectRow(row) {
      if (this.isSelected(row)) {
        this.removeSelected(this.selectedRows.indexOf(row)); // 如果已经选中，则移除
      } else {
        this.selectedRows.push(row); // 否则，添加到选中列表
      }
    },
    // 判断某一行是否已被选中
    isSelected(row) {
      return this.selectedRows.includes(row);
    },
    // 移除已选中的项目
    removeSelected(index) {
      this.selectedRows.splice(index, 1); // 移除已选中的行
    },
    handleDealer() { // 处理已选中的公司
      this.publicPublicityForm.dealer = this.selectedRows[0].departmentName;
      this.editPublicityForm.dealer = this.selectedRows[0].departmentName;
      this.selectedRows = [];
      this.dialogDealerVisible = false; // 关闭对话框
    },
    handleLook(row) { // 查看
      console.log(row);
      this.LookPublicityForm = row
      this.LookPublicityForm.title = `${row.projectName}（招标项目编号${row.projectNumber}）`
      this.LookPublicityForm.budget = row.budget
      this.LookPublicityForm.procurementMethod = row.procurementMethod
      this.dialogLookVisible = true
    },
    handleEdit(row) { // 编辑
      this.editPublicityForm = row
      this.$set(this.editPublicityForm,"title", `${row.projectName}（招标项目编号${row.projectNumber}）`)
      this.$set(this.editPublicityForm,"budget", row.budget)
      this.$set(this.editPublicityForm,"procurementMethod", row.procurementMethod)
      this.$set(this.editPublicityForm,"publicityFileUrl", row.publicityFileUrl)
      this.$set(this.editPublicityForm,"dateRange", [row.publicityDate.split(" - ")[0], row.publicityDate.split(" - ")[1]])
      this.dialogEditVisible = true
    },
    saveEdit() { // 保存编辑
      const dateStr1 = this.editPublicityForm.dateRange[0];
      const date1 = new Date(dateStr1);
      const formattedDate1 = date1.toISOString().slice(0, 10);
      const dateStr2 = this.editPublicityForm.dateRange[1];
      const date2 = new Date(dateStr2);
      const formattedDate2 = date2.toISOString().slice(0, 10);
      this.editPublicityForm.publicityStartTime=formattedDate1
      this.editPublicityForm.publicityEndTime=formattedDate2
      this.editPublicityForm.projectNumber = this.editPublicityForm.publicityName.split("{")[1].split("+")[0]
      this.editPublicityForm.publicityFileUrl = this.fileUrl !== '' ? this.fileUrl : this.editPublicityForm.publicityFileUrl
      addPublicity(this.editPublicityForm).then(res => {
        if(res){
          this.$message.success('修改公示成功')
        }else {
          this.$message.error('操作失败')
        }
      })
      this.dialogEditVisible = false
      this.init()
    },
    confirmDelete(row) {
      this.$confirm('您确定要删除该项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            this.handleDelete(row); // 调用删除方法
          })
          .catch(() => {
            this.$message.info('已取消删除')
          });
    },
    handleDelete(row) { // 删除
      console.log(row)
      deletePublicityByName(row.publicityName).then(res => {
        if(res){
          this.$message.success('删除成功')
          this.updateForm.projectNumber = row.projectNumber
          this.updateForm.status = 3
          addProject(this.updateForm)
          this.init()
          this.init()
        }else {
          this.$message.error('删除失败')
        }
      })
    },
    handleAnnounFile(row){
      this.fileUrl = row
      this.$message.success('文件添加成功')
    },
    handleAnnounFileError(err, file, fileList) {
      console.log(file)
      // 上传失败的处理逻辑
      this.$message.error('文件上传失败，请重试');
    },
    reset() { // 重置
      this.projectNumber = "";
      this.projectName = "";
      this.init();
    },
  }
}
</script>

<style scoped>
>>> .slide-right-dialog {
  top: -150px;
  right: 0;
  margin: 0;
  position: absolute;
  height: 2000px;
  width: 600px;
  animation: slide-right 0.3s ease;
}

>>> .slide-right-dialog .el-dialog__title {
  font-size: 20px; /* 调整对话框正文内容的字体大小 */
}
@keyframes slide-right {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}
.x {
  display: flex;
  justify-content: space-between;
}

.y {
  width: 45%;
}

.z {
  width: 45%;
  border-left: 1px solid #ccc;
  padding-left: 20px;
}
</style>